{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "https://mp.weixin.qq.com/s?__biz=MzkxODE3NjExOQ==&mid=2247485442&idx=1&sn=3fdebeb8a5b8fb5023b7517e6f4df978&chksm=c1b4201af6c3a90c294aca5de40033cb0ca2231d25d021f21ad32218c7f67986be35131561ae&scene=178&cur_album_id=3354758663365918722#rd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入需要使用的库\n",
    "import akshare as ak\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "# 关闭警告信息\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')\n",
    "\n",
    "# 设置取数日期范围\n",
    "start_date = '20140101'\n",
    "end_date = '20231229'\n",
    "# 获取基准指数的收盘价数据\n",
    "benchmark = \"000300\"\n",
    "bars = ak.stock_zh_index_hist_csindex(symbol=benchmark, start_date=start_date, end_date=end_date)\n",
    "# 将日期设置为datetime格式\n",
    "bars['日期'] = pd.to_datetime(bars['日期'])\n",
    "prices_df = pd.DataFrame(index=bars['日期'])\n",
    "prices_df[f'{benchmark}'] = bars.set_index('日期')['收盘']\n",
    "\n",
    "# 获取股票的收盘价数据\n",
    "stock = \"600519\"\n",
    "bars = ak.stock_zh_a_hist(symbol=stock, period=\"daily\", start_date=start_date, end_date=end_date, adjust=\"qfq\")\n",
    "# 将日期设置为datetime格式\n",
    "bars['日期'] = pd.to_datetime(bars['日期'])\n",
    "prices_df[f'{stock}'] = bars.set_index('日期')['收盘']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "回归法是参照资本资产定价模型（CAPM）建立回归方程，CAPM模型表述了预期回报与市场风险之间的关系，  \n",
    "其公式为：Rp = Rf + βi * (Rm - Rf)  \n",
    "其中：  \n",
    "Rp=资产收益率  \n",
    "Rm=市场收益率  \n",
    "Rf=无风险利率  \n",
    "βi=资产beta值  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-2.8040920709406376 4.526100005564257\n"
     ]
    }
   ],
   "source": [
    "#用回归法计算阿尔法和贝塔值\n",
    "# 用回归法计算阿尔法和贝塔，假设无风险报酬率为0\n",
    "# 导入需要的库\n",
    "import statsmodels.api as sm\n",
    "\n",
    "# 年化期数，一年约244个交易日\n",
    "annual_periods = 244  \n",
    "# 计算基准和标的股票的日收益率\n",
    "returns = prices_df.pct_change().fillna(0)\n",
    "\n",
    "# 为线性回归的自变量（市场的回报率）添加常数项\n",
    "X = sm.add_constant(returns[f'{benchmark}'])\n",
    "# 运行回归分析\n",
    "model = sm.OLS(returns[f'{stock}'], X).fit()\n",
    "# 贝塔值是市场回报率的回归系数\n",
    "beta = model.params[f'{benchmark}']\n",
    "# 阿尔法值是回归截距，乘以年化期数进行简单年化处理\n",
    "alpha = model.params['const'] * annual_periods\n",
    "\n",
    "print(alpha, beta)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "用协方差 / 方差法计算阿尔法和贝塔值  \n",
    "Beta = Cov(R_asset, R_market) / Var(R_market)  \n",
    "其中：\n",
    "Cov(R_asset, R_market)为资产回报率与市场回报率协方差  \n",
    "Var(R_market)为市场回报率的方差  \n",
    "\n",
    "Alpha = Rp − [Rf + βi * (Rm − Rf)]  \n",
    "其中： \n",
    "Rp=资产收益率  \n",
    "Rm=市场收益率  \n",
    "Rf=无风险利率  \n",
    "βi=资产beta值  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-2.8040920709406354 4.526100005564257\n"
     ]
    }
   ],
   "source": [
    "# 用协方差 / 方差法计算阿尔法和贝塔值，假设无风险报酬率为0\n",
    "# 年化期数，一年约244个交易日\n",
    "annual_periods = 244  \n",
    "# 计算基准和标的股票的日收益率\n",
    "returns = prices_df.pct_change().fillna(0)\n",
    "\n",
    "# 计算returns和benchmark的协方差矩阵，这个矩阵包含了两个序列的方差和协方差\n",
    "matrix = np.cov(returns[f'{stock}'], returns[f'{benchmark}'])\n",
    "# 贝塔 = 资产回报率与基准回报率之间的协方差 / 基准回报率的方差\n",
    "beta = matrix[0, 1] / matrix[1, 1]\n",
    "# 阿尔法 = 资产回报率均值 - 贝塔 * 基准回报率均值\n",
    "alpha = returns[f'{stock}'].mean() - beta * returns[f'{benchmark}'].mean()\n",
    "# 乘以年化期数进行简单年化处理\n",
    "alpha = alpha * annual_periods\n",
    "\n",
    "print(alpha, beta)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "4broker",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
